﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using YAPL.Language.Core.Types;
using YAPL.Util;
using Ast = YAPL.Language.Ast;
using YAPL.Language.Compiler.CodeGen.ReflectionEmitGenerator.AstGen.Helpers;

namespace YAPL.Language.Compiler.CodeGen.ReflectionEmitGenerator.AstGen {
	public class ReAssignmentGenerator : ReExpressionGenerator {
		public ReAssignmentGenerator(ReCodeGenerator codeGenerator) : base(codeGenerator) {}
		public override void Generate(Ast.Expression expr) {
			var assignmentExpr = (Ast.AssignmentExpression) expr;
			var ilGen = Generator.Get<ILGenerator>(ReCodeGenerator.IL_GENERATOR_KEY);

			//Require.HasType(assignmentExpr.Left, typeof(Ast.VariableExpression), "left side of assignment should be variable");
			var variable = (Ast.BaseIdentifierExpression) assignmentExpr.Left;

			Generator.EmitExpression(assignmentExpr.Right);
			ilGen.Emit(OpCodes.Stloc_0);
			if (variable is Ast.VariableExpression) {
				ilGen.EmitSetLocalScopeVariable(variable.Name);
			} else {
				ilGen.EmitGetLocalVariableFromScope(YAPLFunction.SELF_PARAMETER);
				ilGen.EmitSetInstanceVariable(variable.Name);
			}
		}
	}
}
